﻿using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Common.Base;
using Common.Helper;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;

namespace Common.Contexts
{
    public class DefaultDbContext : DbContext
    {
        public DefaultDbContext(DbContextOptions options) : base(options)
        {
        }

        // private readonly IdWorker _idWorker;

        // public TestDbContext(DbContextOptions<TestDbContext> options, IdWorker idWorker) : base(options)
        // {
        //     _idWorker = idWorker;
        // }

        // protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        // {
        //     // 清除跟踪的实体状态
        //     // ChangeTracker.Clear();
        //     base.OnConfiguring(optionsBuilder);
        // }
        //
        // private IServiceProvider GetServiceProvider()
        // {
        //     return this.GetInfrastructure();
        // }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            // // 配置所有继承自BaseEntity的实体
            // foreach (var entityType in modelBuilder.Model.GetEntityTypes()
            //              .Where(t => typeof(BaseEntity).IsAssignableFrom(t.ClrType)))
            // {
            //     modelBuilder.Entity(entityType.ClrType)
            //         .Property("CreatedTime")
            //         .HasDefaultValueSql("GETDATE()"); // 数据库生成默认值
            //
            //     modelBuilder.Entity(entityType.ClrType)
            //         .Property("UpdatedTime")
            //         .HasDefaultValueSql("GETDATE()");
            // }
        }

        #region 自动填充

        public override int SaveChanges(bool acceptAllChangesOnSuccess)
        {
            AutoFill();
            return base.SaveChanges(acceptAllChangesOnSuccess);
        }

        public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken())
        {
            AutoFill();
            return base.SaveChangesAsync(cancellationToken);
        }

        public override Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess,
            CancellationToken cancellationToken = new CancellationToken())
        {
            AutoFill();
            return base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken);
        }

        // 重写SaveChanges方法实现自动填充
        public override int SaveChanges()
        {
            AutoFill();
            return base.SaveChanges();
        }

        private void AutoFill()
        {
            var entries = ChangeTracker.Entries()
                .Where(e => e.Entity is BaseEntity &&
                            (e.State == EntityState.Added || e.State == EntityState.Modified));
            // using var scope = GetServiceProvider().CreateScope();
            // var scopeServices = scope.ServiceProvider;
            // var idWorker = scopeServices.GetRequiredService<IdWorker>();

            foreach (var entityEntry in entries)
            {
                var entity = (BaseEntity)entityEntry.Entity;

                if (entityEntry.State == EntityState.Added)
                {
                    // entity.KeyId = _idWorker.NextId().ToString();
                    if (entity.KeyId <= 0 || entity.KeyId == null)
                    {
                        entity.KeyId = IdWorkerHelper.NextId();
                    }

                    entity.IsDeleted = 0;
                    entity.CreateTime = DateTime.Now;
                    entity.CreateUserId = UserContext.UserId;
                }

                entity.UpdateTime = DateTime.Now;
                entity.UpdateUserId = UserContext.UserId;
            }
        }

        #endregion
    }
}